import random
import requests
import re as match
from lxml import etree


class ValueGenerater:
    def __init__(self):
        self.__source = None
        self.__answers = {}
        self.__data = None

    def __get_value(self):
        xpath_selector = etree.HTML(self.__source)
        xpath_selector = xpath_selector.xpath(
            '//div[@id="ctl00_ContentPlaceHolder1_JQ1_surveyContent"]/fieldset/div[@class="div_question"]')

        for selector in xpath_selector:
            div = selector.xpath("./div[@class='div_table_radio_question']")[0]
            id = div.xpath("../div[@class='div_table_radio_question']/@id")[0]
            id = match.search('(\d+)', id).group()

            if len(div.xpath('./table')) == 0:
                self.__process_single_question(id, div)
            else:
                self.__process_multi_question(id, div)

    def __process_single_question(self, id, element):
        num = len(element.xpath('./ul/li'))
        self.__answers[id] = str(random.randint(1, num))

    def __process_multi_question(self, id, element):
        selectors = element.xpath('./table/tbody/tr')
        j = 1
        data = ''
        for selector in selectors:
            num = len(selector.xpath('./td'))
            data = data + '%s!%s,' % (j, str(random.randint(1, num)))
            j = j+1
        self.__answers[id] = data[:-1]



    def __generate_values(self):
        data = ''
        for i in self.__answers.keys():
            data = data + '%s$%s}' % (i, self.__answers[i])
        self.__data = data[:-1]

    def exec(self,source):
        # self.__set_header()
        # self.__get_source()
        self.__source = source
        self.__get_value()
        self.__generate_values()
        return self.__data
    
